<!DOCTYPE html>
<html lang="zh">
    <head>
    <!--
        © Material Theme
        https://github.com/viosey/hexo-theme-material
        Version: 1.3.4 -->

    <!-- Title -->
    
    <title>
        
            Java网络编程 | 
        
        Twilight&#39;s Blog
    </title>

    <!-- Meta & Info -->
    <meta charset="utf-8">

    <!-- dns prefetch -->
    <meta http-equiv="x-dns-prefetch-control" content="on">
    
    
        <link rel="dns-prefetch" href="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"/>
    
    
        <link rel="dns-prefetch" href="https://changyan.sohu.com"/>
    
    
    
    

    <meta http-equiv="X-UA-Compatible">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="theme-color" content="#0097A7">
    <meta name="author" content="wangchao">
    <meta name="description" content="null">
    <meta name="keywords" content="null,Java">

    <!-- Favicons -->
    <link rel="icon shortcut" type="image/ico" href="/img/favicon.png">
    <link rel="icon" sizes="192x192" href="/img/favicon.png">
    <link rel="apple-touch-icon" href="/img/favicon.png">

    <!--iOS -->
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <meta name="apple-mobile-web-app-title" content="Title">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="480">

    <!-- Add to homescreen for Chrome on Android -->
    <meta name="mobile-web-app-capable" content="yes">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Twilight&#39;s Blog">

    <!-- The Open Graph protocol -->
    <meta property="og:url" content="http://yoursite.com">
    <meta property="og:type" content="blog">
    <meta property="og:title" content="Java网络编程 | Twilight&#39;s Blog">
    <meta property="og:description" content="null">
    <meta property="og:article:tag" content="Java"> 

    <!--[if lte IE 9]>
        <link rel="stylesheet" href="/css/ie-blocker.css">

        
            <script src="/js/ie-blocker.zhCN.js"></script>
        
    <![endif]-->

    <!-- Import CSS & jQuery -->
    
        <link rel="stylesheet" href="/css/material.min.css">
        <link rel="stylesheet" href="/css/style.min.css">
        <!-- Config CSS -->


<!-- Other Styles -->
<style>
  body, html {
    font-family: Roboto, "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }

  a {
    color: #00838F;
  }

  .mdl-card__media,
  #search-label,
  #search-form-label:after,
  #scheme-Paradox .hot_tags-count,
  #scheme-Paradox .sidebar_archives-count,
  #scheme-Paradox .sidebar-colored .sidebar-header,
  #scheme-Paradox .sidebar-colored .sidebar-badge{
    background-color: #0097A7 !important;
  }

  /* Sidebar User Drop Down Menu Text Color */
  #scheme-Paradox .sidebar-colored .sidebar-nav>.dropdown>.dropdown-menu>li>a:hover,
  #scheme-Paradox .sidebar-colored .sidebar-nav>.dropdown>.dropdown-menu>li>a:focus {
    color: #0097A7 !important;
  }

  #post_entry-right-info,
  .sidebar-colored .sidebar-nav li:hover > a,
  .sidebar-colored .sidebar-nav li:hover > a i,
  .sidebar-colored .sidebar-nav li > a:hover,
  .sidebar-colored .sidebar-nav li > a:hover i,
  .sidebar-colored .sidebar-nav li > a:focus i,
  .sidebar-colored .sidebar-nav > .open > a,
  .sidebar-colored .sidebar-nav > .open > a:hover,
  .sidebar-colored .sidebar-nav > .open > a:focus,
  #ds-reset #ds-ctx .ds-ctx-entry .ds-ctx-head a {
    color: #0097A7 !important;
  }

  .toTop {
    background: #757575 !important;
  }

  .material-layout .material-post>.material-nav,
  .material-layout .material-index>.material-nav,
  .material-nav a {
    color: #757575;
  }

  #scheme-Paradox .MD-burger-layer {
    background-color: #757575;
  }

  #scheme-Paradox #post-toc-trigger-btn {
    color: #757575;
  }

  .post-toc a:hover {
    color: #00838F;
    text-decoration: underline;
  }

</style>


<!-- Theme Background Related-->

    <style>
      body{
        background-image: url(/img/bg.jpg);
      }
    </style>




<!-- Fade Effect -->

    <style>
      .fade {
        transition: all 800ms linear;
        -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
        -ms-transform: translate3d(0,0,0);
        -o-transform: translate3d(0,0,0);
        transform: translate3d(0,0,0);
        opacity: 1;
      }

      .fade.out{
        opacity: 0;
      }
    </style>


        <script src="/js/jquery.min.js"></script>
        <script src="/js/queue.js"></script>
    

    <!-- UC Browser Compatible -->
    <script>
        var agent = navigator.userAgent.toLowerCase();
        if(agent.indexOf('ucbrowser')>0) {
            document.write("<link rel=\"stylesheet\" href=\"/css/uc.css\">");
            alert('由于 UC 浏览器使用极旧的内核，而本网站使用了一些新的特性。\n为了您能更好的浏览，推荐使用 Chrome 或 Firefox 浏览器。');
        }
    </script>

    

    


    <!-- Bing Background -->
    

    <!-- Custom Head -->
    
</head>


    
        <body id="scheme-Paradox" class="lazy">
            <div class="material-layout  mdl-js-layout has-drawer is-upgraded">
                

                <!-- Main Container -->
                <main class="material-layout__content" id="main">

                    <!-- Top Anchor -->
                    <div id="top"></div>

                    
                        <!-- Hamburger Button -->
                        <button class="MD-burger-icon sidebar-toggle">
                            <span class="MD-burger-layer"></span>
                        </button>
                    

                    <!-- Post TOC -->

    
    <!-- Back Button -->
    <!--
    <div class="material-back" id="backhome-div" tabindex="0">
        <a class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon"
           href="#" onclick="window.history.back();return false;"
           target="_self"
           role="button"
           data-upgraded=",MaterialButton,MaterialRipple">
            <i class="material-icons" role="presentation">arrow_back</i>
            <span class="mdl-button__ripple-container">
                <span class="mdl-ripple"></span>
            </span>
        </a>
    </div>
    -->

    <!-- Left aligned menu below button -->
    <button id="post-toc-trigger-btn"
        class="mdl-button mdl-js-button mdl-button--icon">
        <i class="material-icons">format_list_numbered</i>
    </button>

    <ul class="post-toc-wrap mdl-menu mdl-menu--bottom-left mdl-js-menu mdl-js-ripple-effect" for="post-toc-trigger-btn" style="max-height:80vh; overflow-y:scroll;">
        <ol class="post-toc"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#端口号"><span class="post-toc-number">1.</span> <span class="post-toc-text">端口号</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#URL"><span class="post-toc-number">2.</span> <span class="post-toc-text">URL</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#数据的传输"><span class="post-toc-number">3.</span> <span class="post-toc-text">数据的传输</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#InetAddress-表示互联网的IP地址"><span class="post-toc-number">4.</span> <span class="post-toc-text">InetAddress 表示互联网的IP地址</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#URL-1"><span class="post-toc-number">5.</span> <span class="post-toc-text">URL</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#UDP"><span class="post-toc-number">6.</span> <span class="post-toc-text">UDP</span></a></li></ol>

        <!--
        <li class="mdl-menu__item">
            Some Action
        </li>
        -->
    </ul>




<!-- Layouts -->

    <!-- Post Module -->
    <div class="material-post_container">

        <div class="material-post mdl-grid">
            <div class="mdl-card mdl-shadow--4dp mdl-cell mdl-cell--12-col">

                <!-- Post Header(Thumbnail & Title) -->
                
    <!-- Paradox Post Header -->
    
        
            <!-- Random Thumbnail -->
            <div class="post_thumbnail-random mdl-card__media mdl-color-text--grey-50">
            <script>
    var randomNum = Math.floor(Math.random() * 19 + 1);

    $('.post_thumbnail-random').attr('data-original', '/img/random/material-' + randomNum + '.png');
    $('.post_thumbnail-random').addClass('lazy');
</script>

        
    
            <p class="article-headline-p">
                Java网络编程
            </p>
        </div>





                
                    <!-- Paradox Post Info -->
                    <div class="mdl-color-text--grey-700 mdl-card__supporting-text meta">

    <!-- Author Avatar -->
    <div id="author-avatar">
        <img src="/img/avatar.png" width="44px" height="44px" alt="Author Avatar"/>
    </div>
    <!-- Author Name & Date -->
    <div>
        <strong>wangchao</strong>
        <span>12月 10, 2016</span>
    </div>

    <div class="section-spacer"></div>

    <!-- Favorite -->
    <!--
        <button id="article-functions-like-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon btn-like">
            <i class="material-icons" role="presentation">favorite</i>
            <span class="visuallyhidden">favorites</span>
        </button>
    -->

    <!-- Qrcode -->
    

    <!-- Tags (bookmark) -->
    
    <button id="article-functions-viewtags-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
        <i class="material-icons" role="presentation">bookmark</i>
        <span class="visuallyhidden">bookmark</span>
    </button>
    <ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="article-functions-viewtags-button">
        <li class="mdl-menu__item">
        <a class="post_tag-link" href="/tags/Java/">Java</a>
    </ul>
    

    <!-- Share -->
    <button id="article-fuctions-share-button" class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
    <i class="material-icons" role="presentation">share</i>
    <span class="visuallyhidden">share</span>
</button>
<ul class="mdl-menu mdl-menu--bottom-right mdl-js-menu mdl-js-ripple-effect" for="article-fuctions-share-button">
    
    <!-- Leancloud Views -->
        <a class="post_share-link" href="#">
            <li class="mdl-menu__item">
                <span id="/2016/12/10/网络编程/" class="leancloud-views_num" data-flag-title="Java网络编程">
     &nbsp;浏览量
</span>

            </li>
        </a>
    

    

    <!-- Share Weibo -->
    
        <a class="post_share-link" href="http://service.weibo.com/share/share.php?appkey=&title=Java网络编程&url=http://yoursite.com//2016/12/10/网络编程/index.html&pic=&searchPic=false&style=simple" target="_blank">
            <li class="mdl-menu__item">
                分享到微博
            </li>
        </a>
    

    <!-- Share Twitter -->
    
        <a class="post_share-link" href="https://twitter.com/intent/tweet?text=Java网络编程&url=http://yoursite.com//2016/12/10/网络编程/index.html&via=wangchao" target="_blank">
            <li class="mdl-menu__item">
                分享到 Twitter
            </li>
        </a>
    

    <!-- Share Facebook -->
    
        <a class="post_share-link" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com//2016/12/10/网络编程/index.html" target="_blank">
            <li class="mdl-menu__item">
                分享到 Facebook
            </li>
        </a>
    

    <!-- Share Google+ -->
    
        <a class="post_share-link" href="https://plus.google.com/share?url=http://yoursite.com//2016/12/10/网络编程/index.html" target="_blank">
            <li class="mdl-menu__item">
                分享到 Google+
            </li>
        </a>
    

    <!-- Share LinkedIn -->
    

    <!-- Share QQ -->
    
        <a class="post_share-link" href="http://connect.qq.com/widget/shareqq/index.html?site=Twilight&#39;s Blog&title=Java网络编程&summary=null&pics=http://yoursite.com/img/favicon.png&url=http://yoursite.com/2016/12/10/网络编程/index.html" target="_blank">
            <li class="mdl-menu__item">
                分享到 QQ
            </li>
        </a>
    

    <!-- Share Telegram -->
    
</ul>

</div>

                

                <!-- Post Content -->
                <div id="post-content" class="mdl-color-text--grey-700 mdl-card__supporting-text fade out">
    
        <h4 id="端口号"><a href="#端口号" class="headerlink" title="端口号"></a>端口号</h4><p>两个字节，范围0~65535</p>
<p>1、在同一个协议下端口号不能重复<br>2、1024以下的端口号不要使用</p>
<a id="more"></a>
<h4 id="URL"><a href="#URL" class="headerlink" title="URL"></a>URL</h4><p>统一资源定位符</p>
<blockquote>
<p>URI 统一资源</p>
</blockquote>
<h4 id="数据的传输"><a href="#数据的传输" class="headerlink" title="数据的传输"></a>数据的传输</h4><p>1、协议  TCP/UDP<br>    1) TCP（transfer control protocol） 面向连接 安全可靠，效率低下<br><br>    2) UDP（userDatagram Protocol） 非面向连接 效率高 数据可能丢失</p>
<p>2、数据<br>    先封装/后拆分</p>
<hr>
<p>1、InetAddress InetSockAddress<br>2、URL<br>3、TCP：serverSocker Socket<br>4、UDP：DatagramSocket DatagramPacket</p>
<h4 id="InetAddress-表示互联网的IP地址"><a href="#InetAddress-表示互联网的IP地址" class="headerlink" title="InetAddress 表示互联网的IP地址"></a><strong>InetAddress 表示互联网的IP地址</strong></h4><p>getHostAddress()返回IP地址<br>getHostName() 返回域名/本机为计算机名<br>InetAddress.getLocalHost()返回本机地址<br>InetAddress.getByName(“192.168.1.1”); ip/域名</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">// InetAddress</div><div class="line">	public static void main (String [] args) throws UnknownHostException&#123;</div><div class="line">		InetAddress inet = InetAddress.getLocalHost();</div><div class="line">		System.out.println(inet.getHostName());</div><div class="line">		System.out.println(inet.getHostAddress());</div><div class="line">		</div><div class="line">		inet = InetAddress.getByName(&quot;twilight.net.cn&quot;);</div><div class="line">		System.out.println(inet.getHostName());</div><div class="line">		System.out.println(inet.getHostAddress());</div><div class="line">		</div><div class="line">		inet = InetAddress.getByName(&quot;151.101.16.133&quot;);</div><div class="line">		System.out.println(inet.getHostName());</div><div class="line">		System.out.println(inet.getHostAddress());</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p>InetSocketAddress 套接字（ip + 端口号）</p>
<blockquote>
<p>SocketAddress是一个抽象类，类中没有方法</p>
</blockquote>
<p>1、创建对象</p>
<blockquote>
<p>InetSocketAddress(InetAddress addr,int port)<br>根据主机名和端口号创建套接字地址。<br>InetSocketAddress(InetAddress addr, int port)<br>根据 IP 地址和端口号创建套接字地址。<br>InetSocketAddress(int port)<br>创建套接字地址，其中 IP 地址为通配符地址，端口号为指定值。</p>
</blockquote>
<p>2、方法</p>
<blockquote>
<p>getAddress() 获取InetAddress<br>getHostName() 计算机名<br>getHostAddress() 返回地址<br>getPort() 获得端口号</p>
</blockquote>
<pre><code>//InetSocketAddress
public static void main(String[] args) throws UnknownHostException {
    InetSocketAddress net = new InetSocketAddress(&quot;127.0.0.1&quot;, 2000);
    System.out.println(net.getPort());
    System.out.println(net.getHostName());
    System.out.println(net.getAddress().getHostAddress());
}
</code></pre><h4 id="URL-1"><a href="#URL-1" class="headerlink" title="URL"></a><strong>URL</strong></h4><p>组成： 协议+存放资源的主机域名+端口+资源名</p>
<p>创建：<br>URL(String apec)  绝对路径构建<br>URL (URL context,String s) 相对路径构建<br>URL(String protocol, String host, int port, String file) 根据指定 协议、主机号、端口号、和文件创建 URL 对象。</p>
<p>getProtocol() 获取协议<br>getHost() 获取主机名<br>getPort() 获取端口<br>getFile() 获取文件名<br>getPath() 获取<br>getRef()  锚点锚点<br>getQuery() 获取查询部分（参数存在锚点返回null，不存在返回正确）</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span> <span class="params">(String [] args)</span> <span class="keyword">throws</span> MalformedURLException</span>&#123;</div><div class="line">	URL address = <span class="keyword">new</span> URL(<span class="string">"http://www.baidu.com:80/index.html#abc"</span>);</div><div class="line">	System.out.println(<span class="string">"协议"</span> + address.getProtocol());</div><div class="line">	System.out.println(<span class="string">"文件名"</span>+address.getFile());</div><div class="line">	System.out.println(<span class="string">"主机"</span>+address.getHost());</div><div class="line">	System.out.println(<span class="string">"端口"</span>+address.getPort());</div><div class="line">	System.out.println(<span class="string">"路径"</span>+address.getPath());</div><div class="line">	System.out.println(<span class="string">"锚点"</span>+address.getRef());</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><em>运行结果：</em><br><em>协议 http</em><br><em>文件名 /index.html</em><br><em>主机 www.baidu.com</em><br><em>端口 80</em><br><em>路径 /index.html</em><br><em>锚点 abc</em></p>
<p>获取资源：<br><em>主页/默认资源</em><br>InputStream openStream() 获取网络流</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span> <span class="params">(String [] args)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">	URL address = <span class="keyword">new</span> URL(<span class="string">"https://www.baidu.com/index.html"</span>);</div><div class="line">	BufferedReader input = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(address.openStream(),<span class="string">"utf-8"</span>));</div><div class="line">	BufferedWriter output = <span class="keyword">new</span> BufferedWriter(<span class="keyword">new</span> OutputStreamWriter(<span class="keyword">new</span> FileOutputStream(<span class="string">"url_1.html"</span>),<span class="string">"utf-8"</span>));</div><div class="line">	<span class="keyword">int</span> len = <span class="number">0</span>;</div><div class="line">	<span class="keyword">byte</span> [] data = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">100</span>];</div><div class="line">	String s = <span class="keyword">null</span>;</div><div class="line">	<span class="keyword">while</span>(<span class="keyword">null</span> != (s = input.readLine()))&#123;</div><div class="line">		output.append(s);</div><div class="line">		output.newLine();</div><div class="line">		output.flush();</div><div class="line">	&#125;</div><div class="line">	input.close();</div><div class="line">	output.close();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<hr>
<p>对于乱码，目前两种解决方法：<br>1：用InputStreamReader转换流 InputStreamReader( inputstream s ,charset )</p>
<blockquote>
<p>例： BufferedReader input = new BufferedReader(new InputStreamReader(address.openStream(),”utf-8”));</p>
</blockquote>
<p>2：用String的构造函数String(byte[] ,charset )将字符数组转化成对应的编码</p>
<blockquote>
<p>例：System.out.println(new String (data,”utf-8”));</p>
</blockquote>
<hr>
<h4 id="UDP"><a href="#UDP" class="headerlink" title="UDP"></a><strong>UDP</strong></h4><p><em>UDP以数据为中心，不安全，数据可能丢失，效率高</em></p>
<p>DatagramSocket DatagramPacket<br>1 客户端</p>
<blockquote>
<p>1&gt;创建DatagramSocket类 + 指定端口<br>2&gt;数据 字节数组<br>3&gt;打包 DatagramPacket 服务器地址端口<br>4&gt;发送<br>5&gt;释放资源</p>
</blockquote>
<p>2 服务器端</p>
<blockquote>
<p>1&gt;创建服务端 DatagramSocket<br>2&gt;准备接受容器，字节数组，封装DatagramPacket<br>3&gt;包接受数据<br>4&gt;分析<br>5&gt;释放</p>
</blockquote>
<hr>
<p>DatagramSocket构造函数：<br><em>此类表示用来发送和接收数据报包的套接字。</em></p>
<blockquote>
<p>DatagramSocket()<br>构造数据报套接字并将其绑定到本地主机上任何可用的端口。<br>DatagramSocket(int port)<br>创建数据报套接字并将其绑定到本地主机上的指定端口。<br>DatagramSocket(int port, InetAddress laddr)<br>创建数据报套接字，将其绑定到指定的本地地址。<br>DatagramSocket(SocketAddress bindaddr)<br>创建数据报套接字，将其绑定到指定的本地套接字地址。 </p>
</blockquote>
<p>DatagramPacket 构造函数:<br><em>此类表示数据报包。</em></p>
<blockquote>
<p>接收：<br>DatagramPacket(byte[] buf, int length)<br>构造 DatagramPacket，用来接收长度为 length 的数据包。 </p>
<p>发送:<br>DatagramPacket(byte[] buf, int length, InetAddress address, int port)<br>构造数据报包，用来将长度为 length 的包发送到指定主机上的指定端口号。<br>DatagramPacket(byte[] buf, int length, SocketAddress address)<br>构造数据报包，用来将长度为 length 的包发送到指定主机上的指定端口号</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 客户端</span></div><div class="line">    ublic <span class="class"><span class="keyword">class</span> <span class="title">testUDPclient</span> </span>&#123;</div><div class="line">    	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">    		DatagramSocket output = <span class="keyword">new</span> DatagramSocket(<span class="number">1234</span>);</div><div class="line">    		<span class="keyword">byte</span> [] data = <span class="string">"UDP数据"</span>.getBytes();</div><div class="line">    		DatagramPacket packet = <span class="keyword">new</span> DatagramPacket(data,data.length,<span class="keyword">new</span> InetSocketAddress(<span class="string">"localhost"</span>,<span class="number">2000</span>));</div><div class="line">    		output.send(packet);</div><div class="line">    		output.close();</div><div class="line">    	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">    <span class="comment">// 服务器端</span></div><div class="line">    <span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">testUDPserver</span> </span>&#123;</div><div class="line">    	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span> <span class="params">(String [] args)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">    		DatagramSocket input = <span class="keyword">new</span> DatagramSocket(<span class="number">2000</span>);</div><div class="line">    		<span class="keyword">byte</span> [] data =  <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">    		DatagramPacket packet = <span class="keyword">new</span> DatagramPacket(data,data.length);</div><div class="line">    		input.receive(packet);</div><div class="line">    		<span class="keyword">byte</span> [] info = <span class="keyword">new</span> <span class="keyword">byte</span> [<span class="number">1024</span>] ;</div><div class="line">    		info = packet.getData();</div><div class="line">    		<span class="keyword">int</span> len = packet.getLength();</div><div class="line">    		System.out.println(<span class="string">"已收到："</span>+<span class="keyword">new</span> String (info,<span class="number">0</span>,len));</div><div class="line">    		</div><div class="line">    		input.close();</div><div class="line">    	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>发送double类型的数据：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//服务器端，将接受的流转换为double型</span></div><div class="line">	<span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">double</span> <span class="title">convert</span> <span class="params">(<span class="keyword">byte</span> [] data)</span> <span class="keyword">throws</span> IOException</span>&#123;</div><div class="line">		DataInputStream input = <span class="keyword">new</span> DataInputStream( <span class="keyword">new</span> ByteArrayInputStream(data));</div><div class="line">		<span class="keyword">double</span> s = input.readDouble();</div><div class="line">		<span class="keyword">return</span> s;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//客户端，将带发送的double型转换为byte数组</span></div><div class="line">	<span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">byte</span> [] convert(<span class="keyword">double</span> num ) <span class="keyword">throws</span> IOException&#123;</div><div class="line">		<span class="keyword">byte</span> [] data = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</div><div class="line">		ByteArrayOutputStream a = <span class="keyword">new</span> ByteArrayOutputStream();</div><div class="line">		DataOutputStream b = <span class="keyword">new</span> DataOutputStream(a);</div><div class="line">		b.writeDouble(num);</div><div class="line">		data = a.toByteArray();</div><div class="line">		<span class="keyword">return</span> data;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p><strong>ByteArrayInputStream 和 ByteArrayOutputStream 将一个字节数组当作流输入、输出的来源</strong></p>
<blockquote>
<p><br><br>ByteArrayInputStream 将字节数组转换为流     byte[]—&gt;流<br>—-read() 将字节数组读取到流中</p>
<p>ByteArrayOutputStream 将将流转换为字节数组  流—&gt; byte[]<br>—-toByteArray() 返回数组<br>—-write(byte [],int off,int len ) 将数组中的数据写入到流中</p>
<p>DataOutputStream 将double类型写入到流中。   double—&gt; 流<br>—-writeXXX() </p>
<p>DataInputStream  从流中读取数据，并转换为相应的类型  流—&gt;double<br>—-readXXX()</p>
</blockquote>
<p>Socket通讯 （基于TCP）<br><em>面向连接，安全可靠，效率低</em></p>
<p>1、面向连接： 请求-相应 request-response<br>2、Socket编程</p>
<p>1&gt;服务器端<br>创建服务器 指定端口 ServerSocket(int port)<br>接受客户连接 accept() 返回Socket类型<br>传递数据</p>
<p>2&gt;客户端<br>创建客户端 指定服务器端+端口 Socket(String s ,int port )<br>传递数据</p>
<p>发送信息：<br>Socket.getOutputStream();<br>write()<br>flush()</p>
<p>接受数据：<br>client.getInputStream();<br>read()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 客户端</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">testTCPclient</span> </span>&#123;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> UnknownHostException, IOException </span>&#123;</div><div class="line">		Socket socket = <span class="keyword">new</span> Socket(<span class="string">"localhost"</span>,<span class="number">2000</span>);</div><div class="line">		String data = <span class="string">"TCP信息"</span>;</div><div class="line"><span class="comment">//		OutputStream output = socket.getOutputStream();</span></div><div class="line">		DataOutputStream output =  <span class="keyword">new</span> DataOutputStream(socket.getOutputStream());</div><div class="line">		</div><div class="line">		output.writeUTF(data);</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//服务器端</span></div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> IOException </span>&#123;</div><div class="line">		ServerSocket socket = <span class="keyword">new</span> ServerSocket(<span class="number">2000</span>);</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			Socket server = socket.accept();</div><div class="line">			System.out.println(<span class="string">"已连接"</span>);</div><div class="line"><span class="comment">//			InputStream input = server.getInputStream();</span></div><div class="line">			DataInputStream input = <span class="keyword">new</span> DataInputStream(server.getInputStream());</div><div class="line">			String s = input.readUTF();</div><div class="line">			System.out.println(s);</div><div class="line">			</div><div class="line">		&#125; <span class="keyword">catch</span> (IOException e) &#123;</div><div class="line">			<span class="comment">// TODO Auto-generated catch block</span></div><div class="line">			System.out.println(<span class="string">"连接失败"</span>);</div><div class="line">		&#125;</div><div class="line">	&#125;</div></pre></td></tr></table></figure>
<p><em>不同的协议之间端口号可以重复，同一个协议中端口号不能重复</em></p>

    

    
</div>


                

                <!-- Post Comments -->
                
                    


    <!-- 使用 changyan -->
    <div id="changyan-comment">
        <!--PC和WAP自适应版-->
<div id="SOHUCS" sid="2016/12/10/网络编程/"  ></div>
<script type="text/javascript">
(function(){
var appid = 'cysVH2p6S';
var conf = '7d191ef850d424bb873df33179309db5';
var width = window.innerWidth || document.documentElement.clientWidth;
if (width < 960) {
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>

    </div>
    <style>
        #changyan-comment{
            background-color: #eee;
            padding: 2pc;
        }
    </style>






                
            </div>

            <!-- Post Prev & Next Nav -->
            <nav class="material-nav mdl-color-text--grey-50 mdl-cell mdl-cell--12-col">
    <!-- Prev Nav -->
    
        <a href="/2016/12/21/初识JavaScript/" id="post_nav-newer" class="prev-content">
            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon mdl-color--white mdl-color-text--grey-900" role="presentation">
                <i class="material-icons">arrow_back</i>
            </button>
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            新篇
        </a>
    

    <!-- Section Spacer -->
    <div class="section-spacer"></div>

    <!-- Next Nav -->
    
        <a href="/2016/12/04/Java线程/" id="post_nav-older" class="next-content">
            旧篇
            &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon mdl-color--white mdl-color-text--grey-900" role="presentation">
                <i class="material-icons">arrow_forward</i>
            </button>
        </a>
    
</nav>

        </div>
    </div>



                    
                        <!-- Overlay For Active Sidebar -->
<div class="sidebar-overlay"></div>

<!-- Material sidebar -->
<aside id="sidebar" class="sidebar sidebar-colored sidebar-fixed-left" role="navigation">
    <div id="sidebar-main">
        <!-- Sidebar Header -->
        <div class="sidebar-header header-cover" style="background-image: url(/img/sidebar_header.jpg);">
    <!-- Top bar -->
    <div class="top-bar"></div>

    <!-- Sidebar toggle button -->
    <button type="button" class="sidebar-toggle mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" style="display: initial;" data-upgraded=",MaterialButton,MaterialRipple">
        <i class="material-icons">clear_all</i>
        <span class="mdl-button__ripple-container">
            <span class="mdl-ripple">
            </span>
        </span>
    </button>

    <!-- Sidebar Avatar -->
    <div class="sidebar-image">
        <img src="/img/avatar.png" alt="wangchao's avatar">
    </div>

    <!-- Sidebar Email -->
    <a data-toggle="dropdown" class="sidebar-brand" href="#settings-dropdown">
        twilight0402@163.com
        <b class="caret"></b>
    </a>
</div>


        <!-- Sidebar Navigation  -->
        <ul class="nav sidebar-nav">
    <!-- User dropdown  -->
    <li class="dropdown">
        <ul id="settings-dropdown" class="dropdown-menu">
            
                <li>
                    <a href="http://mail.163.com" target="_blank" title="Email Me">
                        
                            <i class="material-icons sidebar-material-icons sidebar-indent-left1pc-element">email</i>
                        
                        Email Me
                    </a>
                </li>
            
        </ul>
    </li>

    <!-- Homepage -->
    
        <li id="sidebar-first-li">
            <a href="/" target="_self">
                
                    <i class="material-icons sidebar-material-icons">home</i>
                
                主页
            </a>
        </li>
        
    

    <!-- Archives  -->
    
        <li class="dropdown">
            <a href="#" class="ripple-effect dropdown-toggle" data-toggle="dropdown">
                
                    <i class="material-icons sidebar-material-icons">inbox</i>
                
                    归档
                <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
            <li>
                <a class="sidebar_archives-link" href="/archives/2017/08/">八月 2017<span class="sidebar_archives-count">5</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/07/">七月 2017<span class="sidebar_archives-count">23</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/06/">六月 2017<span class="sidebar_archives-count">13</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/04/">四月 2017<span class="sidebar_archives-count">7</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/03/">三月 2017<span class="sidebar_archives-count">3</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/02/">二月 2017<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/archives/2017/01/">一月 2017<span class="sidebar_archives-count">8</span></a></li><li><a class="sidebar_archives-link" href="/archives/2016/12/">十二月 2016<span class="sidebar_archives-count">4</span></a></li><li><a class="sidebar_archives-link" href="/archives/2016/11/">十一月 2016<span class="sidebar_archives-count">3</span></a></li><li><a class="sidebar_archives-link" href="/archives/2016/09/">九月 2016<span class="sidebar_archives-count">3</span></a>
            </ul>
        </li>
        
    

    <!-- Categories  -->
    
        <li class="dropdown">
            <a href="#" class="ripple-effect dropdown-toggle" data-toggle="dropdown">
                
                    <i class="material-icons sidebar-material-icons">chrome_reader_mode</i>
                
                分类
                <b class="caret"></b>
            </a>
            <ul class="dropdown-menu">
                <li>
                <a class="sidebar_archives-link" href="/categories/CSS/">CSS<span class="sidebar_archives-count">9</span></a></li><li><a class="sidebar_archives-link" href="/categories/HTML/">HTML<span class="sidebar_archives-count">3</span></a></li><li><a class="sidebar_archives-link" href="/categories/JSP/">JSP<span class="sidebar_archives-count">6</span></a></li><li><a class="sidebar_archives-link" href="/categories/Java/">Java<span class="sidebar_archives-count">8</span></a></li><li><a class="sidebar_archives-link" href="/categories/JavaScript/">JavaScript<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/categories/Linux/">Linux<span class="sidebar_archives-count">13</span></a></li><li><a class="sidebar_archives-link" href="/categories/MySQL/">MySQL<span class="sidebar_archives-count">7</span></a></li><li><a class="sidebar_archives-link" href="/categories/Servlet/">Servlet<span class="sidebar_archives-count">9</span></a></li><li><a class="sidebar_archives-link" href="/categories/jQuery/">jQuery<span class="sidebar_archives-count">7</span></a></li><li><a class="sidebar_archives-link" href="/categories/技术/">技术<span class="sidebar_archives-count">2</span></a></li><li><a class="sidebar_archives-link" href="/categories/日常/">日常<span class="sidebar_archives-count">1</span></a></li><li><a class="sidebar_archives-link" href="/categories/随笔/">随笔<span class="sidebar_archives-count">3</span></a>
            </ul>
        </li>
        
    

    <!-- Pages  -->
    
        <li>
            <a href="/tags" title="标签云">
                
                    <i class="material-icons sidebar-material-icons">cloud</i>
                
                标签云
            </a>
        </li>
        
            <li class="divider"></li>
        
    
        <li>
            <a href="/about" title="About">
                
                    <i class="material-icons sidebar-material-icons">person</i>
                
                About
            </a>
        </li>
        
    
        <li>
            <a href="/links" title="Social">
                
                    <i class="material-icons sidebar-material-icons">equalizer</i>
                
                Social
            </a>
        </li>
        
    

    <!-- Article Number  -->
    
        <li>
            <a href="/archives">
                文章总数
                <span class="sidebar-badge">71</span>
            </a>
        </li>
        
    
</ul>


        <!-- Sidebar Footer -->
        <!--
I'm glad you use this theme, the development is no so easy, I hope you can keep the copyright, I will thank you so much.
If you still want to delete the copyrights, could you still retain the first one? Which namely "Theme Material"
It will not impact the appearance and can give developers a lot of support :)

很高兴您使用并喜欢该主题，开发不易 十分谢谢与希望您可以保留一下版权声明。
如果您仍然想删除的话 能否只保留第一项呢？即 "Theme Material"
它不会影响美观并可以给开发者很大的支持和动力。 :)
-->

<!-- Sidebar Divider -->

    <div class="sidebar-divider"></div>


<!-- Theme Material -->


<!-- Help & Support -->
<!--

-->

<!-- Feedback -->
<!--

    <a href="https://github.com/viosey/hexo-theme-material/issues" target="_blank" class="sidebar-footer-text-a">
        <div class="sidebar-text mdl-button mdl-js-button mdl-js-ripple-effect sidebar-footer-text-div" data-upgraded=",MaterialButton,MaterialRipple">
        sidebar.feedback
        <span class="mdl-button__ripple-container"><span class="mdl-ripple"></span></span></div>
    </a>

-->

<!-- About Theme -->
<!--

    <a href="https://blog.viosey.com/index.php/Material.html" target="_blank" class="sidebar-footer-text-a">
        <div class="sidebar-text mdl-button mdl-js-button mdl-js-ripple-effect sidebar-footer-text-div" data-upgraded=",MaterialButton,MaterialRipple">
             sidebar.about_theme
            <span class="mdl-button__ripple-container"><span class="mdl-ripple"></span></span></div>
    </a>

-->

    </div>

    <!-- Sidebar Image -->
    

</aside>

                    

                    
                        <!-- Footer Top Button -->
                        <div class="toTop-wrap">
    <a href="#top" class="toTop">
        <i class="material-icons footer_top-i">expand_less</i>
    </a>
</div>

                    

                    <!--Footer-->
<footer class="mdl-mini-footer" id="bottom">
    
        <!-- Paradox Footer Left Section -->
        <div class="mdl-mini-footer--left-section sns-list">
    <!-- Twitter -->
    
        <a href="https://twitter.com/twitter" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn" style="background-image: url(/img/footer/footer_ico-twitter.svg);">
                <span class="visuallyhidden">Twitter</span>
            </button><!--
     --></a>
    

    <!-- Facebook -->
    
        <a href="https://www.facebook.com/facebook" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn" style="background-image: url(/img/footer/footer_ico-facebook.svg);">
                <span class="visuallyhidden">Facebook</span>
            </button><!--
     --></a>
    

    <!-- Google + -->
    
        <a href="https://www.google.com/" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn" style="background-image: url(/img/footer/footer_ico-gplus.svg);">
                <span class="visuallyhidden">Google Plus</span>
            </button><!--
     --></a>
    

    <!-- Weibo -->
    

    <!-- Instagram -->
    

    <!-- Tumblr -->
    

    <!-- Github -->
    
        <a href="https://github.com/1601436878" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn" style="background-image: url(/img/footer/footer_ico-github.svg);">
                <span class="visuallyhidden">Github</span>
            </button><!--
     --></a>
    

    <!-- LinkedIn -->
    

    <!-- Zhihu -->
    
        <a href="https://www.zhihu.com/people/wang-chao-50-78/activities" target="_blank">
            <button class="mdl-mini-footer--social-btn social-btn" style="background-image: url(/img/footer/footer_ico-zhihu.svg);">
                <span class="visuallyhidden">Zhihu</span>
            </button><!--
     --></a>
    

    <!-- Bilibili -->
    

    <!-- Telegram -->
    
</div>


        <!--Copyright-->
        <div id="copyright">
            Copyright&nbsp;©&nbsp;
            <script type="text/javascript">
                var fd = new Date();
                document.write(fd.getFullYear());
            </script>
            &nbsp;Twilight's Blog
        </div>

        <!-- Paradox Footer Right Section -->

        <!--
        I am glad you use this theme, the development is no so easy, I hope you can keep the copyright.
        It will not impact the appearance and can give developers a lot of support :)

        很高兴您使用该主题，开发不易，希望您可以保留一下版权声明。
        它不会影响美观并可以给开发者很大的支持。 :)
        -->

        <div class="mdl-mini-footer--right-section">
            <div>
                <div class="footer-develop-div">Powered by <a href="https://hexo.io" target="_blank" class="footer-develop-a">Hexo</a></div>
                <div class="footer-develop-div">Theme - <a href="https://github.com/viosey/hexo-theme-material" target="_blank" class="footer-develop-a">Material</a></div>
            </div>
        </div>
    
</footer>


                    <!-- Import File -->

    <script src="/js/lazyload.min.js"></script>
    <script src="/js/js.min.js"></script>



    <script src="/js/nprogress.js"></script>


<script type="text/javascript">
    NProgress.configure({
        showSpinner: true
    });
    NProgress.start();
    $('#nprogress .bar').css({
        'background': '#29d'
    });
    $('#nprogress .peg').css({
        'box-shadow': '0 0 10px #29d, 0 0 15px #29d'
    });
    $('#nprogress .spinner-icon').css({
        'border-top-color': '#29d',
        'border-left-color': '#29d'
    });
    setTimeout(function() {
        NProgress.done();
        $('.fade').removeClass('out');
    }, 800);
</script>





    <!-- Leancloud -->
    <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
    <script>
        AV.initialize('WJXlEXdVypRaytiRUYDL9Q4w-gzGzoHsz', 'qNN24AGgbaMqnDE7lqK8pwCD');
    </script>
    <script>
    function showTime(Counter) {
        var query = new AV.Query(Counter);
        $('.leancloud-views_num').each(function() {
            var url = $(this).attr('id').trim();
            query.equalTo('url', url);
            query.find({
                success: function(results) {
                    if (results.length === 0) {
                        var content = '0 ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                        return;
                    }
                    for (var i = 0; i < results.length; i++) {
                        var object = results[i];
                        var content = object.get('time') + ' ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                    }
                },
                error: function(object, error) {
                    console.log('Error: ' + error.code + ' ' + error.message);
                }
            });
        });
    }

    function addCount(Counter) {
      var Counter = AV.Object.extend('Counter');
      url = $('.leancloud-views_num').attr('id').trim();
      title = $('.leancloud-views_num').attr('data-flag-title').trim();
      var query = new AV.Query(Counter);
      query.equalTo('url', url);
      query.find({
          success: function(results) {
            if (results.length > 0) {
                var counter = results[0];
                counter.fetchWhenSave(true);
                counter.increment('time');
                counter.save(null, {
                    success: function(counter) {
                        var content =  counter.get('time') + ' ' + $(document.getElementById(url)).text();
                        $(document.getElementById(url)).text(content);
                    },
                    error: function(counter, error) {
                        console.log('Failed to save Visitor num, with error message: ' + error.message);
                    }
                });
            } else {
              var newcounter = new Counter();
              newcounter.set('title', title);
              newcounter.set('url', url);
              newcounter.set('time', 1);
              newcounter.save(null, {
                  success: function(newcounter) {
                      console.log('newcounter.get(\'time\')='+newcounter.get('time'));
                      var content = newcounter.get('time') + ' ' + $(document.getElementById(url)).text();
                      $(document.getElementById(url)).text(content);
                  },
                  error: function(newcounter, error) {
                      console.log('Failed to create');
                  }
              });
            }
        },
        error: function(error) {
            console.log('Error:' + error.code + ' ' + error.message);
        }
      });
    }
    $(function() {
        var Counter = AV.Object.extend('Counter');
        if ($('.leancloud-views_num').length === 1) {
            addCount(Counter);
        } else if ($('.post-title-link').length > 1) {
            showTime(Counter);
        }
    });
</script>







    <!-- 畅言公共 js 代码 start -->
		<script id="cy_cmt_num" src="https://changyan.sohu.com/upload/plugins/plugins.list.count.js?clientId=cysVH2p6S">
</script>
    <!-- 畅言公共 js 代码 end -->







<!-- Window Load-->
<script>
    $(window).load(function() {
        // Post_Toc parent position fixed
        $('.post-toc-wrap').parent('.mdl-menu__container').css('position', 'fixed');
    });
</script>

<!-- MathJax Load-->

<script>
    <!-- Offer LazyLoad -->
    queue.offer(function(){
        $('.lazy').lazyload({
            effect : 'show'
        });
    });

    <!-- Start Queue -->
    $(document).ready(function(){
        setInterval(function(){
            queue.execNext();
        },200);
    });
</script>

                </main>
            </div>
			<!--  -->
				<!--<script type="text/javascript" count="200" color="0,0,255" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>-->
			<!--  -->
        </body>
    
</html>
